/**
 * Created by Administrator on 2016/12/8.
 */
import com.sun.mail.util.MailSSLSocketFactory;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;

import javax.imageio.IIOException;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.util.Date;

/**
 * 发送邮件的测试程序
 *
 * @author lwq
 *
 */

public class MailTest {
    private static final String url = "jdbc:mysql://127.0.0.1:3306/dcj?useUnicode=true&useSSL=false";
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String username = "root";
    private static final String password = "root";
    private Connection conn;
    private PreparedStatement ps;
    private ResultSet rs;
    private String sql;
    private MimeMessage mimeMsg = null;
    private static final String sendFrom = "******@tom.com";
    private static final String smtpHost = "smtp.tom.com";

    private Connection Connect(){
        try{
            Class.forName(driver);//load driver
            conn = (Connection)DriverManager.getConnection(url,username,password);
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }catch(SQLException e){
            e.printStackTrace();
        }
        return conn;
    }

    public boolean Insert(String value){
        sql = "insert ignore into mails (Mname) values(?)";
        int i = 0;
        try{
            conn = this.Connect();
            ps = (PreparedStatement) conn.prepareStatement(sql);
            ps.setString(1,value);
            i = ps.executeUpdate();
            ps.close();
            conn.close();
        }catch(SQLException e){
            e.printStackTrace();
        }
        return i>0;
    }
    public List<String> GetAll(){
        sql = "select Mname from mails";
        List<String> list = new ArrayList<String>();
        try{
            conn = this.Connect();
            ps = (PreparedStatement) conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                list.add(rs.getString(1));
            }
            rs.close();
            ps.close();
            conn.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }
    private String getFrom() throws Exception{
        InternetAddress address[] = (InternetAddress[]) mimeMsg.getFrom();
        String from = address[0].getAddress();
        if (from == null)
            from = "";
        return from;
    }
    private void replyMail(Session session,MailTest mail) throws Exception{//回复邮件
        MimeMessage msg = (MimeMessage) mail.mimeMsg.reply(false);
        msg.setFrom(new InternetAddress(sendFrom));
        msg.setRecipients(RecipientType.TO, mail.getFrom());
        Multipart mp = new MimeMultipart();
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setContent("<meta http-equiv=Content-Type content=text/html; charset=GBK>"+
                "您好，您的邮件已经收到，谢谢！", "text/html;charset=gb2312");
        mp.addBodyPart(mbp);
        msg.setContent(mp);
        msg.setSentDate(new Date());
        msg.saveChanges();
        Transport trans = session.getTransport("smtp");
        trans.connect(smtpHost, username, password);
        trans.sendMessage(msg, msg.getAllRecipients());
        trans.close();
    }
    private boolean isNew() throws MessagingException {
        boolean isnew = false;
        Flags flags = ((Message) mimeMsg).getFlags();
        Flags.Flag[] flag = flags.getSystemFlags();
        for (int i = 0; i < flag.length; i++) {
            if (flag[i] == Flags.Flag.SEEN) {
                isnew = true;
                break;
            }
        }
        return isnew;
    }
    public static void main(String[] args) throws MessagingException {
       Connection con=new MailTest().Connect();
        System.out.println();
        MailTest m=new MailTest();
        String []a=new String[3];

        System.out.print(m.GetAll());

        final Properties props = new Properties();
        /*
         * 可用的属性： mail.store.protocol / mail.transport.protocol / mail.host /
         * mail.user / mail.from
         */
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.tom.com");
        // 发件人的账号
        props.put("mail.user", m.GetAll().toArray()[2]);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", "412725dwj");

        // 构建授权信息，用于进行SMTP进行身份验证
       try {
           MailSSLSocketFactory sf = new MailSSLSocketFactory();

        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);}catch (java.security.GeneralSecurityException e){
           e.printStackTrace();
       }
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form = new InternetAddress(
                props.getProperty("mail.user"));
        message.setFrom(form);

        // 设置收件人
        InternetAddress to = new InternetAddress((String) m.GetAll().toArray()[0]);
        message.setRecipient(RecipientType.TO, to);

        // 设置抄送
        InternetAddress cc = new InternetAddress((String) m.GetAll().toArray()[0]);
        message.setRecipient(RecipientType.CC, cc);

        // 设置密送，其他的收件人不能看到密送的邮件地址
       // InternetAddress bcc = new InternetAddress("aaaaa@163.com");
      //  message.setRecipient(RecipientType.CC, bcc);

        // 设置邮件标题
        message.setSubject("测试邮件");
        // 设置邮件的内容体
        message.setContent("How Are You?", "text/html;charset=UTF-8");
        // 发送邮件
        Transport.send(message);
    }
}